package org.millioncall.yueyoga.common.security;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.millioncall.openplatform.util.WebAppUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint;

public class ZhuwLoginUrlAuthenticationEntryPoint extends
		LoginUrlAuthenticationEntryPoint {
	protected Logger logger = LoggerFactory
			.getLogger(ZhuwLoginUrlAuthenticationEntryPoint.class);
	private final RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
	protected boolean enableAjaxResponse = false;

	public ZhuwLoginUrlAuthenticationEntryPoint(String loginFormUrl) {
		super(loginFormUrl);
	}

	@Override
	public void commence(HttpServletRequest request,
			HttpServletResponse response, AuthenticationException authException)
			throws IOException, ServletException {
		String redirectUrl = null;
		if (enableAjaxResponse && WebAppUtils.isAjaxRequest(request)) {
			String msg = "{'success':false,'type':'notAuthenticated','msg':'对不起，您尚未进行用户认证，请先登录'}";
			WebAppUtils.ajaxResponse(response, msg);
		} else {
			if (isUseForward()) {
				if (isForceHttps() && "http".equals(request.getScheme())) {
					redirectUrl = buildHttpsRedirectUrlForRequest(request);
				}
				if (redirectUrl == null) {
					String loginForm = determineUrlToUseForThisRequest(request,
							response, authException);
					if (logger.isDebugEnabled()) {
						logger.debug("Server side forward to: " + loginForm);
					}
					RequestDispatcher dispatcher = request
							.getRequestDispatcher(loginForm);
					dispatcher.forward(request, response);
					return;
				}
			} else {
				redirectUrl = buildRedirectUrlToLoginPage(request, response,
						authException);
			}
			redirectStrategy.sendRedirect(request, response, redirectUrl);
		}
	}

	public boolean isEnableAjaxResponse() {
		return enableAjaxResponse;
	}

	public void setEnableAjaxResponse(boolean enableAjaxResponse) {
		this.enableAjaxResponse = enableAjaxResponse;
	}
}
